package com.jianzh5.action.admin;

import com.jianzh5.action.BaseAction;
import com.jianzh5.common.DataPage;
import com.jianzh5.common.DataTables;
import com.jianzh5.common.ResultJson;
import com.jianzh5.pojo.PAdmin;
import com.jianzh5.pojo.PCase;
import com.jianzh5.pojo.PProduct;
import com.jianzh5.service.CaseServiceI;
import com.jianzh5.service.ProductServiceI;
import com.jianzh5.util.FileUploadUtils;
import com.jianzh5.util.InfoCenterHome;
import com.jianzh5.util.UserUtils;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@Controller
@RequestMapping("/product/case")
public class CaseAction extends BaseAction {
    @Autowired
    private ProductServiceI productService;

    @Autowired
    private CaseServiceI caseService;

    @RequestMapping(value = "/caseList" ,method = RequestMethod.GET)
    @RequiresPermissions("product:case:view")
    public String caseList(){
        return InfoCenterHome.SERVLET_ADMIN_ROOT+"product/caseList";
    }

    @RequestMapping(value = "/caseList",method = RequestMethod.POST)
    @ResponseBody
    public DataTables caseList(DataPage dataPage ,HttpServletRequest request){
        String sindex = request.getParameter("order[0][column]");
        String order = request.getParameter("order[0][dir]");
        String sort = request.getParameter("columns["+sindex+"][data]");
        DataTables dt = caseService.dataTables(order,sort,dataPage);
        return dt;
    }

    @RequestMapping("/editCase")
    @RequiresPermissions("product:case:edit")
    public String editCase(PCase pCase,Model model){
        if(pCase.getId() != 0){
            //编辑，需加载案例信息
            pCase = caseService.getPCase(pCase.getId());
            model.addAttribute("pCase",pCase);
        }
        return InfoCenterHome.SERVLET_ADMIN_ROOT+"product/caseEdit";
    }

    @RequestMapping("/caseEdit")
    @ResponseBody
    public ResultJson caseEdit(PCase pCase, HttpServletRequest request){
        PAdmin pAdmin = UserUtils.getUser();
        ResultJson json = new ResultJson();
        try {
            pCase = requestCase(request, pCase);
            caseService.updateCase(pCase,pAdmin);
            json.setSuccess(true);
            json.setMsg("案例编辑成功...");
        } catch (Exception e) {
            logger.error("案例编辑失败",e);
            json.setMsg("案例编辑失败,数据库异常...");
        }
        return json;
    }

    @ResponseBody
    @RequestMapping("/caseDel")
    @RequiresPermissions("product:case:del")
    public ResultJson caseDel(@RequestParam("id") int id,HttpServletRequest request){
        ResultJson json = new ResultJson();
        try{
            caseService.delCase(id,request);
            json.setSuccess(true);
            json.setMsg("案例刪除成功...");
        }catch (Exception e) {
            logger.error("案例刪除失败,数据库异常...",e);
            json.setMsg("案例刪除失败,数据库异常...");
        }
        return json;

    }


    /**
     * 判断是否有文件上传
     * @param request
     * @param pCase
     * @return
     */
    private PCase requestCase(HttpServletRequest request, PCase pCase) throws FileUploadException {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断request是否有文件上传
        if(multipartResolver.isMultipart(request)){
            if (StringUtils.isNotEmpty(pCase.getFilepath())){
                String realPath = request.getSession().getServletContext().getRealPath(pCase.getFilepath());
                System.out.println(realPath);
                FileUtils.deleteQuietly(new File(realPath));
            }
            String fileNames[];
            fileNames = FileUploadUtils.saveFile((MultipartHttpServletRequest) request, "/case", new String[]{"jpg", "png", "gif", "jpeg", "bmp"});
            if(fileNames != null && fileNames.length == 1){
                pCase.setFilepath(fileNames[0]);
            }
        }
        return pCase;
    }

}
